package FlyweightMode;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 享元模式
 */
public class FlyWeightTest {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(4, 5, TreeFactory.getTree("韩世凯", "爱刘雪"));
        System.out.println(treeNode);

        TreeNode treeNode2 = new TreeNode(3, 5, TreeFactory.getTree("韩世凯", "爱刘雪"));
        System.out.println(treeNode2);


        TreeNode treeNode3 = new TreeNode(46, 56, TreeFactory.getTree("韩世凯", "爱刘雪"));
        System.out.println(treeNode3);
    }
}

class Tree{
    private String name;
    private String data;
    private Tree tree;

    public Tree(String name, String data) {
        System.out.println("tree" + name + "已经创建");
        this.name = name;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }
}


class TreeNode{
    private int x;
    private int y;
    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "x=" + x +
                ", y=" + y +
                ", tree=" + tree +
                '}';
    }
}

class TreeFactory{
    public static Map<String,Tree> map = new ConcurrentHashMap<>();

    public static Tree getTree(String name, String data){
        if(map.containsKey(name)){
            return map.get(name);
        }
        Tree tree = new Tree(name, data);
        map.put(name, tree);
        return tree;
    }
}